package com.itheima.controller.backend.security.admin;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.entity.Result;
import com.itheima.common.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final String UPLOAD_IMAGES_KEY = "upload:images";  // 上传的图片集合
    private static final String SETMEAL_IMAGES_KEY = "setmeal:images";  // 套餐使用的图片集合

    public CommonController(AliOssUtil aliOssUtil) {
        this.aliOssUtil = aliOssUtil;
    }

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file) {
        log.info("文件上传：{}", file);

        try {
            //获取原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名的后缀
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //构造新文件名称
            String objectName = UUID.randomUUID() + extension;

            byte[] bytes = file.getBytes();
            String url = aliOssUtil.upload(bytes, objectName);

            // 将图片名称存入Redis的上传图片集合
            redisTemplate.opsForSet().add(UPLOAD_IMAGES_KEY, objectName);

            return new Result(true, MessageConstant.UPLOAD_SUCCESS, url);
        } catch (IOException e) {
            log.error("文件上传失败：{}", e.getMessage());
            return new Result(false, MessageConstant.UPLOAD_FAIL);
        }
    }
}
